package com.tarena.lbs.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageQuery;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.service.BusinessService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.utils.PageResultBuilder;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class BusinessServiceImpl implements BusinessService {
    private final BusinessRepository businessRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;


    /*商家分页查询*/
    @Override
    public PageResult<BusinessVO> businessList(BusinessQuery businessQuery) throws BusinessException {
        // 1. 检验用户是否登录
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户未登录，请先登录"));

        // 2. 检查用户角色
        Roles userRole = userPrinciple.getRole();
        if (Roles.SHOP.equals(userRole)) {
            // 商家管理员只能查询当前商家下的所有商家
            AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
            // 3. 判断商家是否存在
            Asserts.isTrue(adminDto == null || adminDto.getBusinessId() == null, new BusinessException("-3", "商家不存在"));
            // 4. 设置查询条件商家Id
            businessQuery.setBusinessId(adminDto.getBusinessId());
        }
        //获取分页数据
        Page<BusinessPO> page = businessRepository.getBusinessPageList(businessQuery);
        //转换为vo列表
        List<BusinessVO> voList = page.getRecords().stream()
                .map(po -> {
                    BusinessVO vo = new BusinessVO();
                    BeanUtils.copyProperties(po, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        //构建分页结果
        PageResult<BusinessVO> result =new PageResult<>(businessQuery);
        result.setTotal(page.getTotal());
        result.setObjects(voList);
        return result;
    }
    /*新增商家*/
    @Override
    public void saveBusiness(BusinessParam param) throws BusinessException {
        //用户登录判定
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户未登录，请先登录"));
        //检查用户角色
        Roles userRole = userPrinciple.getRole();
        Asserts.isTrue(!Roles.ADMIN.equals(userRole), new BusinessException("-3", "只有管理员才能创建商家"));
        //检查商家名称是否重复
        int count = businessRepository.countByBusinessName(param.getBusinessName());
        Asserts.isTrue(count > 0, new BusinessException("-4", "商家名称已存在，请使用其他名称"));
        //添加功能实现
        BusinessPO po = new BusinessPO();
        BeanUtils.copyProperties(param, po);
        businessRepository.save(po);
        //绑定图片信息
        if (param.getImageFileUuids() != null && !param.getImageFileUuids().isEmpty()) {
            List<PicUpdateParam> picParams = new ArrayList<>();
            for (String fileUuid : param.getImageFileUuids()) {
                PicUpdateParam picUpdateParam = new PicUpdateParam();
                picUpdateParam.setFileUuid(fileUuid);
                picUpdateParam.setBusinessId(po.getId());
                picUpdateParam.setBusinessType(1);
                picParams.add(picUpdateParam);
            }
            boolean result = attachApi.batchUpdateBusiness(picParams);
            if (!result) {
                throw new BusinessException("-5", "绑定图片信息失败");
            }
        }
    }
    /*商家详情查询*/
    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) throws BusinessException{
        LambdaQueryWrapper<BusinessPO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BusinessPO::getId, businessId);
        BusinessPO businessPO = businessRepository.selectOne(queryWrapper);
        if (businessPO == null) {
            throw new BusinessException("-1", "商家不存在");
        }
        BusinessStoreVO businessStoreVO = new BusinessStoreVO();
        BeanUtils.copyProperties(businessPO, businessStoreVO);

        //通过商家ID获取店铺列表
        List<StorePO> storePOList =businessRepository.getStoreListByBusinessId(businessId);
        List<StoreVO> storeVOList = storePOList.stream()
                .map(storePO -> {
                    StoreVO storeVO = new StoreVO();
                    BeanUtils.copyProperties(storePO, storeVO);
                    return storeVO;
                })
                .collect(Collectors.toList());
                businessStoreVO.setStoreVOList(storeVOList);
        return businessStoreVO;
    }
    /*修改商家信息*/
    @Override
    public void updateBusiness(Integer businessId, BusinessParam param) throws BusinessException {
        // 检验用户是否登录
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户未登录，请先登录"));
        // 检查用户角色，仅平台管理员可操作
        Roles userRole = userPrinciple.getRole();
        Asserts.isTrue(!Roles.ADMIN.equals(userRole), new BusinessException("-3", "只有平台管理员才能更新商家信息"));

        // 检查商家是否存在
        BusinessPO businessPO = businessRepository.selectById(businessId);
        Asserts.isTrue(businessPO == null, new BusinessException("-1", "商家不存在"));

        // 更新商家信息
        BeanUtils.copyProperties(param, businessPO);
        businessRepository.updateById(businessPO);

        // 绑定图片信息
        if (param.getImageFileUuids() != null && !param.getImageFileUuids().isEmpty()) {
            List<PicUpdateParam> picParams = new ArrayList<>();
            for (String fileUuid : param.getImageFileUuids()) {
                PicUpdateParam picUpdateParam = new PicUpdateParam();
                picUpdateParam.setFileUuid(fileUuid);
                picUpdateParam.setBusinessId(businessId);
                picUpdateParam.setBusinessType(1);
                picParams.add(picUpdateParam);
            }
            boolean result = attachApi.batchUpdateBusiness(picParams);
            if (!result) {
                throw new BusinessException("-5", "绑定图片信息失败");
            }
        }
    }
    /*删除商家*/

    @Override
    public void deleteBusiness(Integer businessId) throws BusinessException {
        // 检验用户是否登录
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户未登录，请先登录"));
        // 检查用户角色，仅平台管理员可操作
        Roles userRole = userPrinciple.getRole();
        Asserts.isTrue(!Roles.ADMIN.equals(userRole), new BusinessException("-3", "只有平台管理员才能删除商家"));

        // 检查商家是否存在
        BusinessPO businessPO = businessRepository.selectById(businessId);
        Asserts.isTrue(businessPO == null, new BusinessException("-1", "商家不存在"));

        // 删除商家
        businessRepository.deleteById(businessId);
    }
}





